import { defineStore } from "pinia";
import { replaceFields, flattenDeep } from "@/utils/iterate";
import { get } from "lodash";
import { getCurrentUserNav } from "@/api/login.js";

const { DEV } = import.meta.env;

function getIdentificationPath(data = {}) {
  const val = String(get(data, "url_code") || "").trim();
  if (!val) return;
  const routes = getVueGlobalProperty("$router").getRoutes();
  for (let i = 0, len = routes.length; i < len; i++) {
    let idf = get(routes[i], "meta.identification");
    if (!Array.isArray(idf)) {
      idf = [idf];
    }
    if (idf.indexOf(val) >= 0) {
      let path = get(routes[i], "path");
      return path == "/frame" ? path + `?identification=${val}` : path;
    }
  }
}

export const menuStore = defineStore("menu", {
  state: () => ({
    menus: [],
    identifications: "",
  }),
  actions: {
    async getMenuAsync() {
      let data = getVueGlobalProperty("handleCommonResult")(
        await getCurrentUserNav().catch(() => {
          getVueGlobalProperty("$message").error("菜单获取失败，请稍后再试！");
          this.identifications = [];
        })
      );
      const menus = replaceFields(data[0].nodes, {
        key: (item) => getIdentificationPath(item) || "id-" + item.id, //路由地址
        children: "nodes",
        icon: "img_url",
        title: "name",
      });
      const identifications = flattenDeep(data, {
        getter: (item) => item.nodes,
        format: (item) => item.url_code,
      });
      this.menus = menus;
      this.identifications = identifications; //能进行访问的页面
    },
  },
});
